/*
 * @Description: 模板引擎的编译原理
 * @Version: 1.0
 * @Autor: ziwei
 * @Date: 2021-04-06 09:21:46
 * @LastEditors: ziwei
 * @LastEditTime: 2021-04-25 14:00:27
 */
//new Function + with来实现的
//const ejs = require('ejs');
//const util = require('utl');
const fs = require('fs');
const util = require('util');
const read = util.promisify(fs.readFile);

/* let ejs = {
    async renderFile(filename,options){
        let content = await read(filename,'utf8');
        content.replace(/<%=(.+?)%>/g,function() {
          console.log("arguments",options[arguments[1]]);
          return options[arguments[1]];
        });
        return content;
    }
}; */

//复杂的情况
let ejs = {
  async renderFile(filename, options) {
    let content = await read(filename, 'utf8');
    content = content.replace(/<%=(.+?)%>/g, function () {
      return '${' + arguments[1] + '}'; // 获取对应的内容做这件事
    });
    let head = 'let str = "";\nwith(obj){\n str+=`';
    let body = (content = content.replace(/<%(.+?)%>/g, function () {
      return '`\n' + arguments[1] + '\nstr+=`';
    }));
    let tail = '`} return str';
    let fn = new Function('obj', head + body + tail);
    return fn(options);
  },
};

(async function () {
  let r = await ejs.renderFile('4.NODE-MODULE/template.html', {
    arr: [1, 2, 3],
  });
  console.log(r);
})();

//用ejs直接渲染模板
/* ( async function () {
  let r = await ejs.renderFile('4.NODE-MODULE/template.html',{name:'zf',age:12});
  console.log(r);
})() */
